<template>
  <div class="layout">
    <Layout>
      <div class="wrapper-header">
        <Menu mode="horizontal" theme="dark" class="header-menu" @on-select="clickMenu" ref="child">
          <div class="layout-logo">
            <img src="../../assets/bbmg/mainpage/logo1.png" style="width: 266px; height:42px">
          </div>
          <div class="layout-nav">
            <MenuItem v-for="(obj , j ) in menudatas" :key="j" :name="obj.menuId">
              {{ obj.menuName }}
            </MenuItem>
          </div>
          <div class="user-name">
            <Select clearable filterable style="width:200px" v-model="currentCompanyId" placeholder="请选择企业"
                    :remote-method="remotedMethod"
                    @on-query-change="remoteMethodSelectOrg"
                    @on-change="selectRemoteOrg"
                    :loading="orgLoading">
              <Option v-for="(option, index) in orgLists" :value="option.orgId" :key="index">{{option.orgName}}
              </Option>
            </Select>
            <Divider type="vertical" style="margin: 0 10px"/>
            <Tooltip>
              <Badge :count="noticeSize" :offset="offsetNum" overflow-count="99" id="todo">
                <a href="javascript:void(0)" style="color: white" @click="toFeedback" content="Top Left text">
                  <Icon type="ios-hand" size="22"/>
                </a>
              </Badge>
              <template #content>
                <p>我要提问</p>
              </template>
            </Tooltip>
            <Divider type="vertical" style="margin: 0 10px"/>
            <Tooltip>
              <Badge :count="noticeSize" :offset="offsetNum" overflow-count="99" id="todo">
                <a href="javascript:void(0)" style="color: white" @click="toNotice">
                  <Icon type="ios-alarm" size="22"/>
                </a>
              </Badge>
              <template #content>
                <p>消息中心</p>
              </template>
            </Tooltip>
            <Divider type="vertical" style="margin: 0 10px"/>
            <Tooltip>
              <Badge :count="todoSize" :offset="offsetNum" overflow-count="99" id="todo">
                <a href="javascript:void(0)" style="color: white" @click="toTodo">
                  <Icon type="ios-notifications" size="22"/>
                </a>
              </Badge>
              <template #content>
                <p>我的待办</p>
              </template>
            </Tooltip>
            <Divider type="vertical" style="margin: 0 10px"/>
            <Dropdown transfer="transfer" @on-click="skipDrop">
              <a href="javascript:void(0)" style="color: rgba(255,255,255,.7);">
                {{ userName }}
                <Icon type="md-arrow-dropdown"/>
              </a>
              <DropdownMenu slot="list">
                <DropdownItem>
                  <a href="" @click.prevent="MyMessige()">
                    我的信息
                  </a>
                </DropdownItem>
                <DropdownItem>
                  <a href="" @click.prevent="modifyCurrentOrg()">
                    切换组织机构
                  </a>
                </DropdownItem>
                <DropdownItem>
                  <a href="javascript:void(0)" @click="dropClick">
                    登出
                  </a>
                </DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        </Menu>
      </div>
      <div class="wrapper-container">
        <router-view ref="childs" v-if="isRouterAlive" @refreshTodo="queryTooltip" @refreshNotice="queryNotice"></router-view>
      </div>
      <Modal v-model="modal3" :width=600 :transfer=false
             title="切换组织机构">
        <Form label-position="top">
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="23">
              <FormItem label="当前公司：" prop="companyId">
                <Select style="width: 100%" v-model="currentOrg.companyId" @on-change="companyIdChanged">
                  <Option v-for="item in userCompanys" :key="item.companyId" :value="item.companyId"
                          :label="item.discard=='1'?item.companyName+'(废弃)':item.companyName"></Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="23">
              <FormItem label="当前部门：" prop="orgId">
                <Select style="width: 100%" v-model="currentOrg.orgId" @on-change="orgIdChanged">
                  <Option v-for="item in userOrgInfos" :key="item.orgId" :value="item.orgId"
                          :label="item.orgName"></Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div slot="footer" class="footer-buttun">
          <Button class='ivu-btn-save' :loading="buttonLoading"
                  @click="makeSureCurrentOrg()">确定
          </Button>
          <Button class='ivu-btn-cancel' @click="cancelCurrentOrg">取消</Button>
        </div>
      </Modal>
      <Modal v-model="modal2" :width=800 :transfer=false
             title="我的信息">
        <Form ref="formCustom" :model="formCustom" :rules="ruleCustom" label-position="top">
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="11">
              <FormItem label="姓名：" prop="userName">
                <Input type="text" v-model="formCustom.userName" readonly></Input>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="登录账号：" prop="loginId">
                <Input type="text" v-model="formCustom.loginId" readonly></Input>
              </FormItem>
            </Col>
          </Row>
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="11">
              <FormItem label="所属公司：" prop="companyId">
                <Input type="text" v-model="formCustom.mainCompanyName" readonly></Input>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="所属部门：" prop="orgId">
                <Input type="text" v-model="formCustom.mainOrgName" readonly></Input>
              </FormItem>
            </Col>
          </Row>
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="11">
              <FormItem label="手机：" prop="mobileNumber">
                <Input type="text" v-model="formCustom.mobileNumber"></Input>
              </FormItem>
            </Col>

            <Col span="11">
              <FormItem label="岗位：" prop="positionId">
                <Select style="width: 100%" v-model="formCustom.positionId" @on-open-change="queryPosition">
                  <Option v-for="item in positions" :key="item.positionId" :value="item.positionId"
                          :label="item.positionName"></Option>
                </Select>
              </FormItem>
            </Col>
          </Row>
          <Row type="flex" justify="space-around" class="code-row-bg">
            <Col span="11">
              <FormItem label="密码：" prop="password">
                <Input type="password" password v-model="formCustom.password"></Input>
              </FormItem>
            </Col>
            <Col span="11">
              <FormItem label="确定密码：" prop="password1">
                <Input type="password" password v-model="formCustom.password1"></Input>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <div slot="footer" class="footer-buttun">
          <Button class='ivu-btn-save' :loading="buttonLoading"
                  @click="submit()">确定
          </Button>
          <Button class='ivu-btn-cancel' @click="modalcancel">取消</Button>
        </div>
      </Modal>

      <Modal v-model="modal4" :width=800 :transfer=false
             title="我要反馈">
        <Form ref="formCustom2" :model="formCustom" :rules="ruleCustom" label-position="top">
          <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
              <i-col span="12">
                  <FormItem label='问题类型：' prop='problemType'>
                      <Select class="query-form-el" placeholder="请选择事件类型" type='text' v-model='formCustom.problemType' >
                          <Option v-for="item in problemTypeList" :value="item.codingCodeId" :key="item.codingCodeId">{{ item.codingName }}</Option>
                      </Select>
                  </FormItem>
              </i-col>
              <i-col span="12">
              </i-col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
                <i-col span="24">
                    <FormItem label='问题描述：' prop='problemDescription'>
                        <Input class='' type='textarea' v-model='formCustom.problemDescription' :rows="4"/>
                    </FormItem>
                </i-col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg" :gutter="16">
              <i-col span="24">
                <FormItem label='附件上传：'>
                  <Upload ref="upload"
                        :before-upload="beforeUpload1"
                        :show-upload-list="true"
                        :max-size="10240"
                        :format="['jpg','jpeg','png']"
                        multiple
                        type="drag"
                        :action="fileUrl">
                    <div style="padding: 10px">
                      <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                      <p>点击将文件拖拽到这里上传</p>
                      <span style="font-size:8px;color: #797a64">支持扩展名：.jpg .jpeg .png</span>
                    </div>
                  </Upload>
                  <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                  <a @click="downloadFile1(dataToView.id,item)">{{ item.fileName }}</a>
                  <Button type="text" icon="md-trash" @click="remove1(item.id)"
                          style="margin-left: 5px;margin-bottom: 3px"/>
                </div>
                </FormItem>
              </i-col>
            </Row>

            
        </Form>
        <div slot="footer" class="footer-buttun">
          <Button class='ivu-btn-save' :loading="buttonLoading"
                  @click="submitProblem()">确定
          </Button>
          <Button class='ivu-btn-cancel' @click="modal4 = false">取消</Button>
        </div>
      </Modal>

    </Layout>
  </div>
</template>
<script>
import {Api} from '../../api/index.js'
import {sessionStorage} from '../../common/cacheUtils.js';
import Common from '../../common/user.js';

export default {
  data() {
    return {
      fileUrl: Api.interestedPartiesUserFile,
      uploadList:[],
      isRouterAlive:true,
      timer:'',
      buttonLoading: false,
      positions: [],
      partTimeOrgs: [],
      userCompanys: [],
      userOrgInfos: [],
      modal3: false,
      currentOrg: {},
      ruleCustom: {
        mobileNumber: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.formCustom.mobileNumber))) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        positionId: [{
          validator: (rule, value, callback) => {
            if (this.formCustom.positionId == null || this.formCustom.positionId == '' || this.formCustom.positionId == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        password: [{
          validator: (rule, value, callback) => {
            if (value == "")
              callback();
            var regex = new RegExp("(?=.*[0-9])(?=.*[a-zA-Z]).{9,16}");
            if (value.length < 9 || value.length > 16) {
              callback(new Error("请输入9~16位密码"));
            } else if (!regex.test(value)) {
              callback(new Error("密码必须同时包含字母、数字且至少9位"));
            } else {
              callback();
            }
          },
          required: false,
          trigger: 'blur'
        }],
        password1: [{
          validator: (rule, value, callback) => {
            if (this.formCustom.password != this.formCustom.password1) {
              callback('两次密码输入不一致')
            } else {
              callback()
            }
          },
          required: false,
          trigger: 'blur'
        }],
        problemType: [ { required: true, message: ' ', trigger: 'change' } ],
        problemDescription: [ { required: true, message: ' ', trigger: 'change' } ],

      },
      formCustom: {},
      modal2: false,
      selected: true,
      routerStyle: {
        height: '100%',
        overflowX: 'hidden',
      },
      websock:null,
      height: 0,
      menudatas: [],
      subMenus: [],
      userName: '',
      offsetNum: [20, 4],
      activeName: 'businessPage',
      noticeSize: 0,
      todoSize: 0,
      isCollapsed: false,
      accordion: true,
      path: "",
      activeMenu: '',
      activeKey: '',
      open: [],
      menudata: [],
      orgLists:[],
      orgLoading:false,
      currentCompanyId:"",
      currentClickedMenu:"",
      ws:null,
      modal4: false,
      problemTypeList: [],
    }
  },
  computed: {
    rotateIcon() {
      return [
        'menu-icon',
        this.isCollapsed ? 'rotate-icon' : ''
      ];
    },
    changeIcon() {
      return [
        'menu-icon',
        !this.isCollapsed ? 'change-icon' : ''
      ];
    },
    menuitemClasses() {
      return [
        'menu-item',
        this.isCollapsed ? 'collapsed-menu' : ''
      ]
    }
  },
  async mounted() {
    this.height = window.innerHeight * 0.95 - 60 + 'px';
    var search = window.location.href.split('?')[1];//截取URL？后面的参数
    var params = {};
    if (search != "" && search != undefined) {
      search.split("&").forEach(
          function (val) {
            var arr = val.split("=");
            params[arr[0]] = arr[1];
          }
      )
    }

    var code = params.code
    var status = params.status
    if (code != null && code != 'undefine') {
      this.$http.get(Api.queryToken, {
        params: {
          code: code,
        }
      }).then(res1 => {
        sessionStorage('access_token').set("access_token", res1.data.access_token);
        this.$http.get(Api.queryUserInfo, {
          params: {
            token: res1.data.access_token,
          }
        }).then(async res => {
          res.data.data.orgInfo.mainOrgName = res.data.data.orgInfo.orgName;
          res.data.data.mainCompanyName = res.data.data.companyName;
          res.data.data.mainCompanyCode = res.data.data.companyCode;
          res.data.data.orgInfo.mainOrgId = res.data.data.orgInfo.orgId;
          res.data.data.mainCompanyId = res.data.data.companyId;
          if (res.data.result == 'true') {
            res.data.data.orgInfo.orgId = res.data.data.currentOrgId;
            res.data.data.orgInfo.orgName = res.data.data.currentOrgName;
            res.data.data.companyName = res.data.data.currentCompanyName;
            res.data.data.companyCode = res.data.data.currentCompanyCode;
            res.data.data.companyId = res.data.data.currentCompanyId;
            res.data.data.orgInfo.parentOrgName = res.data.data.currentOrgParentName;
            res.data.data.orgInfo.parentId = res.data.data.currentOrgParentId;
            let data = JSON.stringify(res.data.data);
            sessionStorage('token').set("Authorization", res.data.token);
            sessionStorage('userId').set('userId', data);
            const userInfo = {
              createUserId: res.data.data.userId,
              createUserName: res.data.data.userName,
              createOrgId: res.data.data.orgInfo.orgId,
              createOrgName: res.data.data.orgInfo.orgName
            }
            sessionStorage('paramUserInfo').set('userInfo', JSON.stringify(userInfo));
            this.userName = sessionStorage('userId').getObject('userId').userName;
            document.querySelector('body').setAttribute('style', 'background-color:#fff')
            this.$router.push('/homepage');
            this.getMenu();
            this.queryTooltip();
            this.queryNotice();
            this.queryPosition();
            this.getPartTimeOrg();
            await this.getHandOverUserList();
            // this.openNotic();
              this.init()
		   await this.$http.get(Api.queryCodeDetailBySortId + '/pw-00001', {params: {}}).then((res) => {
				this.problemTypeList = res.data.data;
			});
          } else {
            this.$Message.error('账号/密码错误');
          }
        }).catch(e => {
          console.error(e);
          this.$Message.error('请求失败');
        })
      })
    } else {
      this.userName = sessionStorage('userId').getObject('userId').userName;
      document.querySelector('body').setAttribute('style', 'background-color:#fff')
      this.$router.push('/homepage');
      this.getMenu();
      this.queryTooltip();
      this.queryNotice();
      this.queryPosition();
      this.getPartTimeOrg();
      await this.getHandOverUserList();
      // this.openNotic();
        this.init()
	  await this.$http.get(Api.queryCodeDetailBySortId + '/pw-00001', {params: {}}).then((res) => {
        this.problemTypeList = res.data.data;
      });
    }
  },
  watch:{
      currentCompanyId:function(newData,oldData){
        if(newData == ""){
          let data = sessionStorage('userId').getObject('userId')
          sessionStorage('userId').del('userId');
          data.companyId = data.currentCompanyId
          data.companyCode = data.currentCompanyCode
          data.companyName = data.currentCompanyName
          let data1 = JSON.stringify(data);
          sessionStorage('userId').set('userId', data1);
          if (this.currentClickedMenu == "" || sessionStorage('menu').getObject('menu')[this.currentClickedMenu].menuName == '首页') {
            this.reload();
          } else {
            this.$refs.childs.reload();
          }
        }
      },
  },
  methods: {
    reload(){
      this.isRouterAlive = false
      this.$nextTick(function () {
        this.isRouterAlive = true
      })
    },
    remotedMethod(){

    },
    remoteMethodSelectOrg (query) {
      clearTimeout(this.remoteMethodSelectOrg.timer)
      if (query.trim() && this.orgLists.every(item => item.orgName !== query)) {
        this.remoteMethodSelectOrg.timer = setTimeout(() => {
          this.orgLoading = true;
          this.$http.get(Api.queryOrgList + "?companyId=" + sessionStorage('userId').getObject('userId').currentCompanyId + "&orgName=" + query + "&fromPage=1&pageSize=1000").then(res => {
            this.orgLoading = false;
            this.orgLists = res.data.data;
          }).catch(e => {
            this.orgLoading = false;
            this.$Message.error('请求失败');
          })
        }, 800)
      }
    },
    selectRemoteOrg(val){
      if(val == "" || val == undefined) {
        this.orgLists = [];
        return;
      }
      let data = sessionStorage('userId').getObject('userId')
      sessionStorage('userId').del('userId');
      this.orgLists.forEach(item => {
        if (item.orgId == this.currentCompanyId){
            data.companyId = item.orgId
            data.companyName = item.orgName
            data.companyCode = item.orgCode
        }
      })
      let data1 = JSON.stringify(data);
      sessionStorage('userId').set('userId', data1);
      if (this.currentClickedMenu == "" || sessionStorage('menu').getObject('menu')[this.currentClickedMenu].menuName == '首页') {
        this.reload();
      } else {
        this.$refs.childs.reload();
      }
    },
    openNotic() {
      let _this = this;
      let userId = sessionStorage('userId').getObject('userId').userId;
      _this.$http.get(Api.queryNoticeCount + "/" + userId).then((res) => {
        if (res.data.data != 0){
          _this.$Notice.open({
            name: 'bellNotice',
            render: h => {
              return h('span', [
                '您有' + res.data.data + '条新的消息请前往',
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                  },
                  on: {
                    click: () => {
                      _this.$router.push({path: '/notice'});
                      _this.$Notice.destroy()
                    }
                  }
                }, '通知中心'),'查看'
              ])
            },
            duration: 0,
          });
        }
      })

      this.timer = setInterval(function(){

        _this.$http.get(Api.queryNoticeCount + "/" + userId).then((res) => {
          if (res.data.data != 0){
            _this.$Notice.close('bellNotice')
            _this.$Notice.open({
              name: 'bellNotice',
              render: h => {
                return h('span', [
                  '您有' + res.data.data + '条新的消息请前往',
                  h('A', {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      fontSize: '14px',
                    },
                    on: {
                      click: () => {
                        _this.$router.push({path: '/notice'});
                      }
                    }
                  }, '通知中心'),'查看'
                ])
              },
              duration: 0,
            });
          }
        })
      }, 20*60*1000);
    },
      init(){
         let userId = sessionStorage('userId').getObject('userId').userId;
         this.ws = this.useWebSocket(handleMessage,userId);
         let _self = this
         function handleMessage(evt) {
             if (evt.data) {
                 let data = JSON.parse(evt.data)
                 _self.$Notice.open({
                     render: h => {
                         return h('span', [
                             data.msg,
                             h('A', {
                                 props: {
                                     type: 'primary',
                                     size: 'small'
                                 },
                                 style: {
                                     fontSize: '14px',
                                 },
                                 on: {
                                     click: () => {
                                         _self.$http.get(Api.UserNoticeRead + "/" + data.id).then((res) => {_self.noticeSize--})
                                         if (data.route) {
                                             _self.$router.push({path: '/modular', query: {id:data.menuId.substr(0, 5),fastMenu:data.route}});
                                         }
                                         _self.$Notice.close(data.id)
                                     }
                                 }
                             }, data.route?'  查看':'')
                         ])
                     },
                     onClose:h => {
                         _self.$http.get(Api.UserNoticeRead + "/" + data.id).then((res) => {_self.noticeSize--})
                     },
                     name:data.id,
                     duration: 0,
                 });
             }
         }
      },

    beforeDestroy() {
        this.$Notice.destroy()
      clearInterval(this.timer);
    },
    modifyCurrentOrg() {
      this.modal3 = true;
      let data = sessionStorage('userId').getObject('userId');
      this.currentOrg.orgId = data.currentOrgId;
      this.currentOrg.companyCode = data.currentCompanyCode;
      this.currentOrg.companyId = data.currentCompanyId;
      this.companyIdChanged(this.currentOrg.companyId);
    },
    makeSureCurrentOrg() {
      let data = sessionStorage('userId').getObject('userId')
      sessionStorage('userId').del('userId');
      data.orgInfo.orgId = this.currentOrg.orgId;
      this.userOrgInfos.forEach(item => {
        if (item.orgId == this.currentOrg.orgId){
          data.orgInfo.orgName = item.orgName
          data.orgInfo.parentId = item.parentId
          data.orgInfo.parentOrgName = item.parentOrgName;
          data.currentOrgId = item.orgId
        }
      })
      this.userCompanys.forEach(item => {
        if (item.companyId == this.currentOrg.companyId) {
          data.companyName = item.companyName
          data.companyCode = item.companyCode
          data.currentCompanyCode = this.currentOrg.companyCode;
        }
      })
      data.currentCompanyId = this.currentOrg.companyId;
      data.companyId = this.currentOrg.companyId;
      let data1 = JSON.stringify(data);
      sessionStorage('userId').set('userId', data1);
      this.modal3 = false;
      var postUserId = sessionStorage('userId').getObject('userId').userId;
      var postOrgId = data.orgInfo.orgId;
      var url = Api.userCurrentOrgId + postUserId + '/' + postOrgId;
      this.$http.post(url,{}).then(res => {}).catch(e => {})
      if (this.currentClickedMenu == "" || sessionStorage('menu').getObject('menu')[this.currentClickedMenu].menuName == '首页') {
        this.reload();
      } else {
        this.$refs.childs.reload();
      }
      this.$http.get(Api.checkEnvInfoComan).then(res => {
        if (res.data.status == '200') {
          sessionStorage('envInfoComan').set('check', res.data.data);
        } else {
          sessionStorage('envInfoComan').set('check', '1');
        }
      }).catch(e => {
        sessionStorage('envInfoComan').set('check', '1');
        console.error(e);
      })
    },
    cancelCurrentOrg() {
      this.modal3 = false;
    }
    ,
    getPartTimeOrg() {
      let userId = sessionStorage('userId').getObject('userId').userId;
      this.$http.get(Api.getPartTimeOrgList + userId).then(res => {
        this.partTimeOrgs = res.data.data;
        this.userCompanys = this.partTimeOrgs;
        this.userOrgInfos = this.partTimeOrgs;
        this.userCompanys = this.userCompanys.filter(function (item, index, self) {
          return self.findIndex(el => el.companyId == item.companyId) === index
        })
      })
    }
    ,
    companyIdChanged(value) {
      if (value == undefined || value == "")
        return;
      this.userOrgInfos = [];
      this.partTimeOrgs.forEach(item => {
        if (item.companyId == value) {
          if(item.discard == '1'){
            this.$http.get(Api.getDepartmentByCompanyId + value).then(res => {
              this.userOrgInfos = res.data.data;
            })
          }else{
            this.userOrgInfos.push({
              orgId: item.orgId, orgName: item.orgName,orgCode:item.orgCode
            })
          }
        }
      })
    },
    orgIdChanged(value) {
    }
    ,
    getMenu() {
      let data = sessionStorage('userId').getObject('userId');
      this.$http.get(Api.getMenusByUser + '/' + data.userId, {params: {orgId:data.companyId}}).then(res => {
        this.menudatas = res.data.data.children;
        let arr = {};
        res.data.data.children.map((item, index) => {
          arr[item.menuId] = item;
        })
        let data = JSON.stringify(arr);
        sessionStorage('menu').set('menu', data);
      }).catch(e => {
        console.log(e)
        this.$Message.error('请求失败');
      })
    }
    ,
    dropClick() {
      let _this = this;
      let userId = sessionStorage('userId').getObject('userId').userId;
      let url = Api.loginOut + "/" + userId;
      this.$http.get(url).then((res) => {
        _this.beforeDestroy();
        _this.$Notice.destroy()
      }).catch(e => {
      })
      sessionStorage('user').del('power')
      sessionStorage('userId').del('userId')
      sessionStorage('token').del('Authorization');
      var access_token = sessionStorage('access_token').get('access_token');
      if (access_token != '') {
        this.$http.get(Api.revokeToken);
        sessionStorage('access_token').del('access_token');
        window.open('about:blank', '_self').close()
      } else
        this.$router.push({path: '/login'});
    }
    ,
    clickMenu(e) {
      this.currentClickedMenu = e;
      if (sessionStorage('menu').getObject('menu')[e].menuName == '首页') {
        this.$router.push({path: '/homepage'})
      } else if (sessionStorage('menu').getObject('menu')[e].menuName.indexOf('驾驶舱') != -1) {
        let routeUrl = this.$router.resolve({
          path: sessionStorage('menu').getObject('menu')[e].menuUrl
        });
        window.open(routeUrl.href, '_blank');
      } else if (sessionStorage('menu').getObject('menu')[e].menuName.indexOf('安环资讯') != -1) {
        this.$router.push({path: '/homepage2'})
      } else {
		   let data = {id: e};
		  let userInfo = sessionStorage('userId').getObject('userId')
		  if (Common.belongOrgId.includes(userInfo.companyId) || Common.jinyuOrgId==userInfo.companyId) {
		  	if (e == '10004') {//安全工作
		  		data.fastMenu='homepageSafe'
		  	}if (e == '10005') {
		  		data.fastMenu='homepageEn'
		  	}
		  } else{
		  	if (e == '10004') {
		  		data.fastMenu='comprehensivePerformance'
		  	}if (e == '10005') {//环保问题台账
          data.fastMenu = 'EnvQuestionAccountStat'
        }
		  }
        this.$router.push({path: '/modular', query: data});
      }
      this.queryTooltip();
      this.queryNotice();
    }
    ,
    async getHandOverUserList(){
      let data = sessionStorage('userId').getObject('userId')
      await this.$http.get(Api.queryUserListByHandedOverUserId + "/" + data.userId).then((res) => {
        data.userBeHandedOver = res.data.data;
      })
      let data1 = JSON.stringify(data);
      sessionStorage('userId').del('userId');
      sessionStorage('userId').set('userId', data1);
      // console.log(data1);
    },
    skipDrop(name) {
      if (name == 'homepage') {
        this.$router.push('/homepage');
        //this.$router.push('/door')
      }
    }
    ,
    toNotice() {
      this.$router.push('/notice');
    }
    ,
    toFeedback(){
      // this.$router.push('/problemFeedbackCenter');
      this.formCustom = {
        id: this.get_uuid()
      };
      this.modal4 = true;

    },
    toTodo() {
      this.$router.push('/todoList');
    }
    ,
    routeTo(e) {
      this.$router.push({path: e});
    }
    ,
    collapsedSider() {
      this.$refs.side1.toggleCollapse();
    }
    ,
    queryTooltip() {
      // let userId = sessionStorage('userId').getObject('userId').userId;
      //  , {params: {createUserId: userId}}
      this.$http.get(Api.procinstCount).then((res) => {
        this.todoSize = res.data.count;
      })
    }
    ,
    queryNotice() {
      let userId = sessionStorage('userId').getObject('userId').userId;
      this.$http.get(Api.queryNoticeCount + "/" + userId).then((res) => {
        this.noticeSize = res.data.data;
      })
    }
    ,
    MyMessige() {
      let user = sessionStorage('userId').getObject('userId');
      this.$set(this.formCustom,'orgId',user.orgInfo.mainOrgId);
      if (user.position != null) {
        this.$set(this.formCustom,'positionId',user.position.positionId);
      }
      this.$set(this.formCustom,'userId',user.userId);
      this.$set(this.formCustom,'userName',user.userName);
      this.$set(this.formCustom,'loginId',user.loginId);
      this.$set(this.formCustom,'mainCompanyName',user.mainCompanyName);
      this.$set(this.formCustom,'mainOrgName',user.orgInfo.mainOrgName);
      this.$set(this.formCustom,'password',"");
      this.$set(this.formCustom,'password1',"");
      this.$set(this.formCustom,'mobileNumber',user.mobileNumber);
      this.$set(this.formCustom,'contactNumber',user.contactNumber);
      this.modal2 = true;
    }
    ,
    submit() {
      this.$refs["formCustom"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          this.formCustom.orgInfo = {"orgId": this.formCustom.orgId};
          this.formCustom.position = {"positionId": this.formCustom.positionId};
          let data = sessionStorage('userId').getObject('userId')
          sessionStorage('userId').del('userId');
          data.mobileNumber = this.formCustom.mobileNumber;
          data.position.positionId = this.formCustom.positionId;
          let data1 = JSON.stringify(data);
          sessionStorage('userId').set('userId', data1);
          this.$http.post(Api.updateUser, this.formCustom).then(res => {
            this.modal2 = false;
            this.formCustom = {};
            this.buttonLoading = false;
            this.$Message.success('成功!');
          }).catch(e => {
            this.buttonLoading = false;
            this.$Message.error('请求失败');
          })

        } else {
          this.$Message.error('不能为空!');
        }
      })
    }
    ,
    modalcancel() {
      this.formCustom = {};
      this.modal2 = false;
    }
    ,
    queryPosition() {
      let data = {
        fromPage: 1,
        pageSize: 1000,
        orgId: sessionStorage('userId').getObject('userId').orgInfo.orgId
      }
      this.$http.get(Api.queryPosition, {
        params: data
      }).then(res => {
        this.positions = res.data.data;
      })
    },
    submitProblem(){
      this.$refs['formCustom2'].validate((valid) => {
        if(valid){
          this.buttonLoading = true;
          this.formCustom.problemNo = sessionStorage('userId').getObject('userId').loginId;
          this.formCustom.problemStatus = 'pw-00002000000001';
          this.formCustom.feedbackUser = sessionStorage('userId').getObject('userId').userName;
          this.formCustom.createUserId = sessionStorage('userId').getObject('userId').userId;
          this.$http.post(Api.saveProblemFeedback, this.formCustom).then(function(res){
              this.$Message.success({
                  content: '保存成功',
                  duration: 4
              });
              this.buttonLoading = false;
              this.modal4 = false;
          }, function(res){
              this.$Message.error({
                  content: '保存失败',
                  duration: 4
              });
          });
        }
      });
    },
    beforeUpload1(file) {
      if(file.type.indexOf("image") == -1){
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: '附件' + file.name + '格式不正确, 请上传jpg或png.'
        });
        return;
      }
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.formCustom.id + '/files/picture'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles1();
        }
      })
      return false
    },
    getFiles1() {
      let url = this.fileUrl + '/' + this.formCustom.id + '/files/picture'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data
        }
      })
    },
    get_uuid() {
        let s = [];
        let hexDigits = "0123456789abcdef";
        for (let i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = "-";

        let uuid = s.join("");
        let reg = new RegExp("-", "g");
        let a = uuid.replace(reg, "");
        return a;
    },
  }
}
</script>

<style scoped>
.layout {
  min-width: 1360px;
  overflow: hidden;
}

#todo >>> .ivu-badge-count {
  font-family: "Monospaced Number";
  line-height: 1;
  vertical-align: middle;
  position: absolute;
  transform: translateX(50%);
  top: -10px;
  right: 0;
  height: 15px;
  border-radius: 8px;
  min-width: 15px;
  background: #48c5fc;
  border: 1px solid transparent;
  color: #fff;
  line-height: 15px;
  text-align: center;
  padding: 0 3px;
  font-size: 12px;
  white-space: nowrap;
  transform-origin: -10% center;
  z-index: 10;
  box-shadow: 0 0 0 1px #fff;
}

.layout-logo {
  width: 150px;
  height: 40px;
  flex-shrink: 0;
  position: relative;
  left: 20px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  margin: auto 0;
}

.layout-nav {
  margin: 0 auto;
  display: flex;
  flex-grow: 1;
  margin-left: 180px;
}

.layout-header {
  padding: 0 0 0 0;
  position: fixed;
  min-width: 100%;
}

.header-menu {
  display: flex;
  height: 64px;
  background-image: url("../../assets/bbmg/mainpage/dark_bg.jpg");
  background-size: cover;
}

.wrapper-header {
  width: 100%;
  z-index: 1000;
}

.wrapper-container {
  width: 100%;
  background: rgb(243, 244, 248);
  box-shadow: 0 1px 1px 0 rgba(0, 0, 0, .1);
}

.user-name {
  flex-shrink: 0;
  margin-right: 20px;
}

@media screen and (min-width: 1601px) {
  .ivu-menu-horizontal .ivu-menu-item, .ivu-menu-horizontal .ivu-menu-submenu {
    padding: 0 20px;
  }
}
@media screen and (min-width: 1360px) and (max-width: 1500px) {
  .ivu-menu-horizontal .ivu-menu-item, .ivu-menu-horizontal .ivu-menu-submenu {
    padding: 0 10px;
  }
}

@media screen and (min-width: 1501px) and (max-width: 1600px) {
  .ivu-menu-horizontal .ivu-menu-item, .ivu-menu-horizontal .ivu-menu-submenu {
    padding: 0 15px;
  }
}

@media screen  and (max-width: 1359px) {
  .ivu-menu-horizontal .ivu-menu-item, .ivu-menu-horizontal .ivu-menu-submenu {
    padding: 0 5px;
  }
}

.ivu-menu-dark.ivu-menu-horizontal .ivu-menu-item {
  font-size: 1rem;
  font-family: Microsoft YaHei;
  color: #FEFBE0;
}

.ivu-menu-dark.ivu-menu-horizontal .ivu-menu-item-active {
  background-color: #CB0A02;
  color: #fff;
}

.ivu-menu-dark.ivu-menu-horizontal .ivu-menu-item:hover {
  background-color: #CB0A02;
  color: #fff;
}

.demo-badge-alone {
  background: #48c5fc !important;
}

</style>
